import moment from "moment";
import {legendEnum} from "./enum";
import {baseLineOption, baseGraphOption} from "./baseEchartsOptions";

export const createLineOption = (data, curStepSelect) => {
	let {datetime: xAxis_data} = data;
	// debugger
	if (!xAxis_data) {
		return {};
	}
	if (curStepSelect.step && curStepSelect.step.includes("hour")) {
		xAxis_data = xAxis_data.map(item => {
			// console.log(moment(item).subtract(8,'hour').format("MM-DD HH:mm"));
			return moment(item).format("MM-DD HH:mm")
		});
	} else {
		xAxis_data = xAxis_data.map(item => {
			// console.log(moment(item));
			return moment(item).format("YYYY-MM-DD")
		});
	}

	const legend_data = Object.keys(data)
		.filter(key => key !== "datetime")
		.map(key => legendEnum[key]);
	const series = Object.keys(data)
		.filter(key => key !== "datetime")
		.map(key => {
			return {
				name: legendEnum[key],
				type: "line",
				stack: "总量",
				data: data[key],
				smooth: true,
				areaStyle: {},
			};
		});

	baseLineOption.legend.data = legend_data;
	baseLineOption.xAxis.data = xAxis_data;
	baseLineOption.series = series;

	return baseLineOption;
};

export const createGraphOption = data => {
	if (!data.topo && !data.collectoies.length) {
		//如果没有节点，中断函数
		const defaultSeriesData = [
			{
				name: "请选择节点",
				info: {
					id: 0,
					level: 0,
					head: true
				},
				symbolSize: 150,
				itemStyle: {color: "#0aa679"}
			}
		];
		baseGraphOption.series[0].data = defaultSeriesData;
		return baseGraphOption;
	}

	let {collectoies, topo} = data; //collectoies为链路所含的所有节点，topo是描述节点关系的json字符串

	const link = JSON.parse(topo); //topo是一个json，这里转换为对象
	const ship = Object.keys(link).filter(key => /-/.test(key));

	const series_data = collectoies.map(item => {
		let {name, id} = item;
		const level = ship.length
			? +ship.find(el => Number(el.split("-")[0]) === id).split("-")[1]
			: 0;
		let symbolSize = 400 - 50 * ship.length - level * 50;
		symbolSize = symbolSize > 150 ? 100 : symbolSize < 60 ? 60 : symbolSize;
		const color = level === 0 ? "#0aa679" : "#1890ff";
		return {
			name: `${name}[${level}级节点]`,
			info: {
				id,
				level: level, //非文档属性，自定义属性，表示节点所处层级，用于节点去重
				head: level === 0 ? true : false //非文档属性，自定义属性，表示节点是否为首节点
			},
			symbolSize: symbolSize,
			itemStyle: {
				color
			}
		};
	});

	let newLink = ship
		.map(linkKey => {
			const id = +linkKey.split("-")[0];
			const sourceIndex = series_data.findIndex(item => item.info.id === id);
			const targetsIndex = link[linkKey].map(targetId => {
				const index = series_data.findIndex(el => el.info.id === targetId);
				return index;
			});

			return {
				source: sourceIndex,
				targets: targetsIndex
			};
		})
		.map(item => {
			let {source, targets} = item;
			return targets.map(target => {
				return {source, target};
			});
		});
	newLink = Array.prototype.concat.apply([], newLink);

	baseGraphOption.series[0].data = series_data;
	baseGraphOption.series[0].links = newLink; //关系依据索引来
	return baseGraphOption;
};
